const Koa = require("koa");
const Router = require("koa-router");
const next = require("next");
const session = require("koa-session");
const Redis = require("ioredis");

const RedisSessionStore = require("./server/session-store");

const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

const redis = new Redis();

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();

  server.keys = ["Github App"];
  const SESSION_CONFIG = {
    key: "jid",
    store: new RedisSessionStore(redis),
  };
  server.use(session(SESSION_CONFIG, server));

  // router.get("/test/:id", (ctx) => {
  //   ctx.body = { success: true };
  //   ctx.set("Content-Type", "application/json");
  // });

  // server.use(async (ctx, next) => {
  //   await next();
  // });

  // server.use(router.routes());

  // server.use(async (ctx, next) => {
  //   ctx.body = `<span>Render Koa</span>`;
  // });
  router.get("/set/user", async (ctx) => {
    ctx.session.user = {
      name: "zzp",
      age: 18,
    };
    ctx.body = "set session success";
  });

  router.get("/delete/user", async (ctx) => {
    ctx.session = null;
    ctx.body = "delete session success";
  });

  server.use(router.routes());

  server.use(async (ctx, next) => {
    await handle(ctx.req, ctx.res);
    ctx.response = false;
  });

  server.listen(3000, () => {
    console.log("koa 3000");
  });
});
